package com.lihua.newideas.service.impl;

import com.lihua.newideas.mapper.MyUserMapper;
import com.lihua.newideas.pojo.MyUser;
import com.lihua.newideas.service.MyUserService;
import com.lihua.newideas.service.PhoneCodeService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MyUserServiceImpl implements MyUserService {
    @Autowired
    private MyUserMapper myUserMapper;
    //加密
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private PhoneCodeService phoneCodeService;

    @Override
    public MyUser queryUserByName(String username) {
        return myUserMapper.queryUserByName(username);
    }

    @Override
    public MyUser insertUser(MyUser user) {
        MyUser myuser = queryUserByName(user.getUserName());
        if(myuser==null){
            user.setPassWord(passwordEncoder.encode(user.getPassWord()));
            myUserMapper.insertUser(user);
            return user;
        }else {
            return null;
        }
    }

    @Transactional
    @Override
    public String updateUserByUserName(String passWord, String userName, String code) {

        MyUser myuser = queryUserByName(userName);
        if(myuser==null){
            return "没有这个用户";
        }else {
            String result = phoneCodeService.isPhoneCode(userName, code);
            if(result.equals("1")){
                String encode = passwordEncoder.encode(passWord);
                myUserMapper.updateUserByUserName(encode,userName);
                //int i =1/0;
                //修改成功
                return "1";
            }else {
                //验证码错误，或者过期
                return result;
            }
        }

    }
    /*根据用户名进行修改*/
    @Override
    public String updateUserByUserName(MyUser user) {
        myUserMapper.updateMyUserByUserName(user);
        return "成功";
    }

    @Override
    public int queryUserNum() {

        return myUserMapper.queryUserNum();
    }

    @Override
    public List<MyUser> queryUserAll() {
        List<MyUser> myUsers = myUserMapper.queryUserAll();
        for (MyUser myUser : myUsers) {
            myUser.setPassWord("");
            myUser.setCode("");
            myUser.setAuthority("");
        }
        return myUsers;
    }

    @Override
    public void deleteMyUserById(int id) {
        myUserMapper.deleteMyUserById(id);
    }

//    @Test
//    public  void test(){
//        System.out.println(updateUserByUserName("456", "123", "123"));
//    }
}
